﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using DGM.Objects.SocialMedia.Twitter;
using DGM.Util.Helpers.Json;
using Newtonsoft.Json.Linq;

namespace DGM.Util.Helpers.Twitter
{
    public static class TwitterStreamHelper
    {
        public static void StreamTrack(string track, Action<Tweet> tweetCallback)
        {
            if (tweetCallback == null)
                return;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://stream.twitter.com/1/statuses/filter.json?track=" + track);
            webRequest.Credentials = new NetworkCredential("McGregorTest", "P@ssw0rd123");
            webRequest.Timeout = -1;
            HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();

            StreamReader responseStream = new StreamReader(webResponse.GetResponseStream());
            while (true)
            {
                var line = responseStream.ReadLine();

                if (string.IsNullOrEmpty(line)) continue;

                JObject o = JObject.Parse(line);

                JObject userObject = (JObject)o["user"];



                var screenName = userObject["screen_name"];

                Tweet result = JsonHelper.GetWellKnownObjectFromJson<Tweet>(line);
                //result.User = JsonHelper.GetWellKnownObjectFromJson<TwitterUser>(userObject);



                tweetCallback(result);
            }
        }
    }
}
